#include "OSSManage.h"
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <memory>
#include <string>


static string endpoint = "oss-cn-beijing.aliyuncs.com";
static string accessKeyId = "LTAI5t9catJnTjtwVSLmVgb7";
static string accessKeySercret = "PAY09SjR3PxXvf1Z3Vzc134wPNSslo";
static string region = "cn-beijing";
static string bucketName = "liin-iporsche";
static string YunRootPath = "disk/";

using AlibabaCloud::OSS::InitializeSdk;
using AlibabaCloud::OSS::ShutdownSdk;
using AlibabaCloud::OSS::PutObjectRequest;
using std::string;

OSSManage::OSSManage()
:conf()
,client(endpoint ,accessKeyId, accessKeySercret, conf)
{
    InitializeSdk();
    client.SetRegion(region);
}

OSSManage::~OSSManage()
{
    ShutdownSdk();
}

void OSSManage::OSSupload(string & filename)
{
    string content;
    int fd = ::open(filename.c_str(),O_RDONLY);
    char buf[4096] = {0};
    int readedNum = 0;
    do{
        readedNum = ::read(fd,buf,4096);
        content.append(buf);
        ::bzero(buf,sizeof(buf));
    }while(readedNum);

    string objectName;
    string::size_type slash = filename.rfind('/');
    if(slash != string::npos){
        objectName = filename.substr(slash+1);
    }

    objectName = YunRootPath + objectName;      //在云端的路径    //还要一个文件路径
    std::shared_ptr<std::iostream> stream = std::make_shared<std::stringstream>(std::move(content));
    PutObjectRequest request {bucketName,objectName,stream};
    auto outcome = client.PutObject(request);
    disposeError(outcome);
    return;
}


void OSSManage::disposeError(const PutObjectOutcome & outcome)
{
    if (!outcome.isSuccess()) {
        /* 异常处理。*/
        std::cout << "PutObject fail" <<
        ",code:" << outcome.error().Code() <<
        ",message:" << outcome.error().Message() <<
        ",requestId:" << outcome.error().RequestId() << std::endl;
    }
    return;
}
